const Redis = require('ioredis')
const GenericPool = require('generic-pool')
const dotenv = require('dotenv')
dotenv.config()

// 重连配置
const retryStrategy = (times) => {
    const delay = Math.min(times * 1000, 5000) // 最大重试间隔5秒
    console.log(`Redis连接失败,第${times}次重试...`)
    return delay
}

const factory = {
    create: () => {
        return new Redis({
            host: process.env.REDIS_HOST,
            port: 6379,
            password: process.env.REDIS_PASSWORD,
            retryStrategy: retryStrategy, // 添加重试策略
            maxRetriesPerRequest: 3, // 每个请求最大重试次数
            reconnectOnError: (err) => {
                // 遇到特定错误时自动重连
                const targetErrors = ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']
                return targetErrors.some(code => err.message.includes(code))
            }
        })
    },
    destroy: (client) => {
        return client.quit()
    }
}

const redisPool = GenericPool.createPool(factory, {
    max: 10,
    min: 2
})

module.exports = redisPool